﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using System.Diagnostics;

namespace predic.UI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainWindow_Loaded);


        }

        string filename = @"c:\!import predic\import7.csv";
        string demo_line = @"Adi Mocan,.,02 - Cum sa ma ridic cand cad mereu in acelasi loc - 2 Petru 1 v19,,verifica calitatea,,,,verif dublura,,,,,22.63,mp3,0,2919,,.,,,,,,,,,,,,,,,,,,";

        private Business.PredicEntities ctx;

        int C_Predicator = 0;
        int C_Studiu = 1;
        int C_PredicaText = 2;
        int C_Text = 3;
        int C_Tematica = 4;
        int C_Subiect = 5;
        //int C_A = 6;
        //int C_B = 7;
        int C_VerificatServer = 8;
        //int C_2M = 9;
        //int C_256 = 10;

        string S_Predicator;
        string S_Studiu;
        string S_PredicaText;
        string S_Text;
        string S_Tematica;
        string S_Subiect;
        //string S_A;
        //string S_B;
        string S_VerificatServer;
        //string S_2M;
        //string S_256;




        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            ctx = new Business.PredicEntities();

            try
            {
                using (StreamReader fileReader = new StreamReader(filename))
                {
                    while (!fileReader.EndOfStream)
                    {
                        try
                        {
                            ProcessLine(fileReader.ReadLine());
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void ProcessLine(string line)
        {
            #region

            string[] tokens = line.Split(',');

            S_Predicator = tokens[C_Predicator];
            S_Studiu = tokens[C_Studiu];
            S_PredicaText = tokens[C_PredicaText];
            S_Text = tokens[C_Text];
            S_Tematica = tokens[C_Tematica];
            S_Subiect = tokens[C_Subiect];
            S_VerificatServer = tokens[C_VerificatServer];

            //Debug.WriteLine(string.Format("*** {0} {1}", predicator, studiu));
            #endregion

            predic.UI.Business.Preacher currentPreacher;

            //adaug predicatorul
            if (!ExistPreacher(S_Predicator))
                currentPreacher = InsertPreacher(S_Predicator);
            else
                currentPreacher = GetPreacher(S_Predicator);


            predic.UI.Business.Study currentStudy = null;

            //adaug studiul
            if (!ExistStudy(currentPreacher.ID, S_Studiu, S_PredicaText))
            {
                currentStudy = InsertStudy(currentPreacher, S_Studiu, S_PredicaText, S_Text, S_Tematica, S_Subiect);

                try
                {
                    InsertStudyDetails(currentStudy, tokens);
                }
                catch
                {
                    Debug.WriteLine(string.Format("Error on Detalii: {0} {1}", currentStudy.Title, currentStudy.Subtitle));
                }
            }

        }

        private void InsertStudyDetails(Business.Study currentStudy, string[] tokens)
        {
            Business.Detail detail = null;
            try
            {

                detail = new Business.Detail()
                 {
                     Study = currentStudy,
                     CheckedAndLoaded = tokens[8],
                     C2M = tokens[9],
                     C256 = tokens[10],
                     CAudio128 = tokens[11],
                     CWithGeneric = tokens[12],
                     CMarime = tokens[13],
                     CA = tokens[14],
                     CNotA = tokens[15],
                     CAIn = tokens[16],
                     CMari = tokens[17],
                     CV = tokens[18],
                     CNotV = tokens[19],
                     CVIn = tokens[20],
                     CNotE = tokens[21],
                     CEIn = tokens[22],
                     CEmbeded = tokens[23],
                     Marime = tokens[24],
                     EAudio = tokens[25],
                     EA = tokens[26],
                     VPhp = tokens[27],
                     EMarime = tokens[28],
                     EVideo = tokens[29],
                     EV = tokens[30],
                     VIn = tokens[31],
                     Embed = tokens[32],
                     BrutAu = tokens[33],
                     BrutVi = tokens[34],
                     PrelucAu = tokens[35],
                     PrelucVi = tokens[36],

                 };
            }
            catch (Exception ex)
            {

            }

            try
            {
                ctx.AddToDetails(detail);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
                //Debug.WriteLine(string.Format("Error on Detalii: {0} {1}", currentStudy.Title, currentStudy.Subtitle));
            }
        }



        private bool ExistPreacher(string name)
        {
            string[] parsedName = name.Split(' ');
            string firstName = parsedName[0].Trim();
            string lastName = parsedName[1].Trim();

            return ctx.Preachers.Where(p => p.FirstName == firstName && p.LastName == lastName).Count() > 0;
        }
        private Business.Preacher InsertPreacher(string name)
        {
            string[] parsedName = name.Split(' ');

            Business.Preacher preacher = new Business.Preacher();
            preacher.FirstName = parsedName[0].Trim();
            preacher.LastName = parsedName[1].Trim();

            ctx.AddToPreachers(preacher);
            ctx.SaveChanges();

            return preacher;
        }
        private Business.Preacher GetPreacher(string name)
        {
            string[] parsedName = name.Split(' ');
            string firstName = parsedName[0].Trim();
            string lastName = parsedName[1].Trim();

            return ctx.Preachers.Where(p => p.FirstName == firstName && p.LastName == lastName).FirstOrDefault();
        }

        private bool ExistStudy(int preacherID, string title, string subtitle)
        {
            return ctx.Studies.Include("Preacher")
                .Where(s => s.Preacher.ID == preacherID && s.Title == title.Trim() && s.Subtitle == subtitle.Trim()).Count() > 0;
        }
        private Business.Study InsertStudy(predic.UI.Business.Preacher preacher, string title, string subtitle, string text, string tematica, string subiect)
        {
            Business.Study study = new Business.Study();
            study.Title = this.FormatTitleOrSubtitle(title.Trim());
            study.Subtitle = this.FormatTitleOrSubtitle(subtitle.Trim());
            study.Preacher = preacher;
            study.Text = text;
            study.Tematica = tematica;
            study.Subiect = subiect;

            ctx.AddToStudies(study);
            ctx.SaveChanges();

            return study;
        }


        private string FormatTitleOrSubtitle(string s)
        {
            string ret = s;

            if (ret.StartsWith("\""))
                ret = ret.Replace("\"", "");

            ret = ret.Replace("@", ",");

            return ret;
        }

    }
}
